﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.IO;

namespace GenY.Internal {
  public class GenYCore {
    [ImportMany]
    public Lazy<IGenYrator, IGenYMetadata>[ ] GenYrators { get; set; }

    public void BootStrap( IEnumerable<String> paths ) {
      var catalog = new AggregateCatalog( new ComposablePartCatalog[ ] { new AssemblyCatalog( this.GetType( ).Assembly ) }.Concat( paths.Select( p => ( ComposablePartCatalog )new DirectoryCatalog( p ) ) ) );
      var container = new CompositionContainer( catalog );
      container.ComposeParts( this );
    }

    public GenyResult Generate( String filename, string contents, string language, String[ ] references ) {
      var extension = Path.GetExtension( filename ).Substring( 1 );
      var gen = GenYrators.FirstOrDefault( g => g.Metadata.Extension.Equals( extension, StringComparison.InvariantCultureIgnoreCase ) );
      if( gen == null )
        throw new ArgumentException( "GenY doesnt know how to handle the extension " + extension );
      return gen.Value.GenYrate( filename, contents, language, references );
    }
  }
}